package com.base.controller.wx_mp_api;

import com.base.helper.WebHelper;
import com.base.po.param.NetState;
import com.base.po.voip.UsersConfig;
import com.base.po.wx.message_send.WXMessageSendRequest;
import com.base.po.wx.message_send.WxMessageSendResponse;
import com.base.service.CarParkService;
import com.base.service.UsersConfigService;
import com.base.utils.Produce;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Map;


/**
 * 微信接口
 *
 * @author K.
 */
@Controller
@RequestMapping("/weixin")
public class Wx_Message_SendController {

    private final CarParkService carParkService;

    private final UsersConfigService usersConfigService;

    private final Wx_TokenController wx_tokenController;

    public Wx_Message_SendController(CarParkService carParkService, UsersConfigService usersConfigService, Wx_TokenController wx_tokenController) {
        this.carParkService = carParkService;
        this.usersConfigService = usersConfigService;
        this.wx_tokenController = wx_tokenController;
    }

    /**
     * 微信 - 公众号推送消息
     */
    @RequestMapping(value = "/messageSend", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState messageSend(HttpServletRequest request, String parentId, String openId, String licensePlate) {
        NetState netState = new NetState();

        if (parentId == null || parentId.equals("")){
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("参数异常");
            return netState;
        }

        // 代理商
        UsersConfig config = null;
        String appId = null;
        String secret = null;
        try {
            config = usersConfigService.selectByParentId(parentId);
            appId = config.getWxMpAppid();
            secret = config.getWxMpAppsecret();
        }catch (Exception e){
            netState.setErrorCode(NetState.NODATA);
            netState.setData("数据异常");
            return netState;
        }

        String accessToken = wx_tokenController.getTokeFromRedis(appId, secret);
        String templateId = "tp7OmHND0dG_IARwCoEGN0gA-hgGURbhupKu8VZdk9c";
        try {
            Boolean isSend = this.getSend(accessToken, openId, licensePlate, templateId);
            if (isSend){
                netState.setErrorCode(NetState.SUCCESS_CONN);
                netState.setData("推送消息成功");
            }else {
                netState.setErrorCode(NetState.SYSTEM_ERROR);
                netState.setData("推送消息失败,无效推送");
            }
        }catch (Exception e){
            netState.setErrorCode(NetState.SYSTEM_ERROR);
            netState.setData("推送消息失败,无效token");
        }

        return  netState;
    }

    public Boolean getSend(String accessToken, String openId, String licensePlate, String templateId){
        Boolean isSend = false;

        WXMessageSendRequest sendRequest = new WXMessageSendRequest();
        sendRequest.setTouser(openId);
        sendRequest.setTemplate_id(templateId);

        Map<String, Object> firstMap = new HashedMap();
        firstMap.put("value", "您好，亲爱的先生/女士");
        firstMap.put("color", "#173177");
        Map<String, Object> keyword1Map = new HashedMap();
        keyword1Map.put("value", licensePlate);
        keyword1Map.put("color", "#173177");
        Map<String, Object> keyword2Map = new HashedMap();
        keyword2Map.put("value", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Produce.getNowDate()));
        keyword2Map.put("color", "#173177");
        Map<String, Object> remarkMap = new HashedMap();
        remarkMap.put("value", "亲，有人请求您挪车，谢谢哦！");
        remarkMap.put("color", "#173177");
        Map<String, Object> dataMap = new HashedMap();
        dataMap.put("first", firstMap);
        dataMap.put("keyword1", keyword1Map);
        dataMap.put("keyword2", keyword2Map);
        dataMap.put("remark", remarkMap);
        JSONObject dataJson = JSONObject.fromObject(dataMap);
        sendRequest.setData(dataJson);
        JSONObject paramJson = JSONObject.fromObject(sendRequest);

        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        try {
            String result = WebHelper.PostData(tokenUrl, paramJson.toString(), "application/json", null);
            WxMessageSendResponse sendResponse = (WxMessageSendResponse) JSONObject.toBean(JSONObject.fromObject(result), WxMessageSendResponse.class);
            if (sendResponse.getErrcode() == 0 && sendResponse.getErrmsg().equals("ok")){
                isSend = true;
            }
        }catch (Exception e){
            isSend = false;
        }

        return isSend;
    }

}
